package com.mango.iot.gateway.tcp.handler.event;

import com.mango.iot.gateway.tcp.handler.Process;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import com.mango.iot.gateway.tcp.connection.Connection;
import com.mango.iot.gateway.tcp.connection.ConnectionManager;
import com.mango.iot.gateway.tcp.message.GpsMessage;
import com.mango.iot.gateway.tcp.utils.ByteUtils;
import com.mango.iot.gateway.tcp.utils.NetUtils;

/**
 * 登录验证包处理 0x01
 *
 * @author liangfeihu
 * @number 53669
 * @since 2021/4/1 下午2:55
 */
@Slf4j
public class HandShake implements Process {

    @Override
    public void execute(GpsMessage msg) throws Exception {

        handleLonginPacket(msg.getDeviceId(), msg.getPacketContent());

        // 构造登录验证响应包
        byte[] replyPacket = NetUtils.buildCommonReplyPacket(msg);

        ChannelHandlerContext ctx = msg.getCtx();
        if (ctx.channel().isWritable()) {
            // 将登录响应包发送出去
            ctx.pipeline().writeAndFlush(Unpooled.wrappedBuffer(replyPacket));
        } else {
            ctx.pipeline().close();
        }

        // 创建连接，存入map管理起来
        setHandShakeConnection(ctx, msg.getDeviceId());
    }

    private void handleLonginPacket(String deviceId, byte[] packetContent) {
        byte[] typeCode = new byte[]{packetContent[8], packetContent[9]};
        byte[] timeCode = new byte[]{packetContent[10], packetContent[11]};
        log.info("[HandShake]deviceId={} deviceType=0x{} timeCode=0x{}", deviceId,
                ByteUtils.bytesToHexString(typeCode), ByteUtils.bytesToHexString(timeCode));
        StringBuilder builder = new StringBuilder();
        int one = 0x00000001 & (packetContent[11] >> 3);
        builder.append(one == 0 ? "东时区" : "西时区").append(" ");


        byte[] timeByte = new byte[]{packetContent[10], (byte) (0xF0 & packetContent[11])};
        int timeInt = byteToInt(timeByte);
        builder.append(timeInt / 100d);
        log.info("[HandShake]deviceId={} timeAndZone={}", deviceId, builder.toString());
    }

    public int byteToInt(byte[] b) {
        return 0x0000FFFF & ((((b[0] & 0xFF) << 8) | (b[1] & 0xFF)) >> 4);
    }

    private void setHandShakeConnection(ChannelHandlerContext ctx, String deviceId) {
        Connection conn = ConnectionManager.getInstance().getConn(deviceId);
        if (conn != null) {
            log.info("已经验证通过,不需要再次验证====mac:{}", conn.getDeviceId());
            return;
        }

        // 新的Connection
        conn = ConnectionManager.getInstance().getNewConnection(ctx);
        boolean ret = conn.isSetDeviceId(deviceId);
        if (!ret) {
            //deviceId设置失败
            log.info("[]conn.setDeviceId失败:{}", deviceId);
            return;
        }
        ConnectionManager.getInstance().addToConnMap(conn.getDeviceId(), conn);
    }

}
